﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace HousingDistribution
{
    public partial class FormPersonDetailsNoHousingTab : Form
    {
        public FormPersonDetailsNoHousingTab()
        {
            InitializeComponent();

            InitControls();

            if (this.curIndex == 0)
                this.buttonPrevious.Enabled = false;
        }


        //初始化人员信息控件
        private void InitControls()
        {
            //初始化DataGridView控件
            InitDGVCurHousing();

            CreateMaritalComboxItem(this.comboBoxMarital);

            //军人tab控件
            CreateUnitComboxItem(this.comboBoxArmManUnit);
            CreateTechRankComboxItem(this.comboBoxArmManTechRank);
            CreateTechTitleComboxItem(this.comboBoxArmManTechTitle);
            CreateArmmanAdmindutyComboxItem(this.comboBoxArmManAdminDuty);
            CreateArmmanEvaluationComboxItem(this.comboBoxArmmanEvaluation);
            CreateOthertypeComboxItem(this.comboBoxArmmanOtherType, PersonTypeEnum.ArmMan);
            CreateWitharmyComboItem(this.comboBoxArmmanWitharmy);

            //职员干部tab控件
            CreateUnitComboxItem(this.comboBoxStaffUnit);
            CreateStaffAdmindutyComboxItem(this.comboBoxStaffAdminDuty);
            CreateStaffTecktitleComboxItem(this.comboBoxStaffTechTitle);
            CreateOthertypeComboxItem(this.comboBoxStaffOtherType, PersonTypeEnum.Staff);

            //工人tab控件
            CreateUnitComboxItem(this.comboBoxWorkerUnit);
            CreateWorkerTechtitleComboxItem(this.comboBoxWorkerTechTitle);
            CreateOthertypeComboxItem(this.comboBoxWorkerOtherType, PersonTypeEnum.Worker);

            //士官tab控件
            CreateUnitComboxItem(this.comboBoxNCOUnit);
            CreateOthertypeComboxItem(this.comboBoxNCOOtherType, PersonTypeEnum.NCO);

            this.comboBoxMarital.Text = DataDictionary.Instance().PersonMaritalStatus()[0];
        }

        private void FormPersonDetailsTab_Load(object sender, EventArgs e)
        {
            //默认显示军人干部
            this.tabControl.SelectTab(this.tabArmMan);

            //数据库中总人数
            this.personCount = GetPersonCount();

            if (this.personCount == 0)
            {
                this.buttonNext.Enabled = false;
                this.buttonDelete.Enabled = false;
            }
            else
                DisplayInfo(this.curIndex);
        }

        private void buttonExit_Click(object sender, EventArgs e)
        {
            //释放资源
            this.personTable = null;
            this.Close();
        }

        private void buttonPersonSearch_Click(object sender, EventArgs e)
        {
            if ( this.textBoxSearch.Text.Length > 0 && this.textBoxSearch.Text!="姓名首字母")
            {
                ResetArmmanInfoTab();
                ResetContrlsBesidesTab();
                ResetNCOInfoTab();
                ResetStaffInfoTab();
                ResetWorkerInfoTab();

                FormPersonSearch searchForm = new FormPersonSearch(this, GetCurPersonType(), this.textBoxSearch.Text);
                searchForm.Show();
            }
        }


        private void buttonPersonSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13 && this.textBoxSearch.Text.Length > 0 && this.textBoxSearch.Text != "姓名首字母")
                {
                    ResetArmmanInfoTab();
                    ResetContrlsBesidesTab();
                    ResetNCOInfoTab();
                    ResetStaffInfoTab();
                    ResetWorkerInfoTab();

                    FormPersonSearch searchForm = new FormPersonSearch(this, GetCurPersonType(), this.textBoxSearch.Text);
                    searchForm.Show();
                }
        }

        private void textBoxSearch_MouseDown(object sender, MouseEventArgs e)
        {
            this.textBoxSearch.Text = null;
        }

        //控制personSearch(姓名搜索)结果中，切换不同人员类别的问题。因为切换tab过程会调用人员显示的tabControl_Selected事件，将默认显示本类别中最后一个人。
        //因此需要设置一个标志位判断是哪一种情况，并且在响应了搜索过程后把标志位变回来。
        bool searchPersonFlag = false;

        public void SetSearchPersonFlag(bool flag)
        {
            this.searchPersonFlag = flag;
        }

        private void tabControl_Selected(object sender, TabControlEventArgs e)
        {
            PersonTypeEnum type = GetCurPersonType();

            if (this.searchPersonFlag == true)
            {
                this.searchPersonFlag = false;
                return;
            }
            this.personTable = null;

            //数据库中总人数
            this.personCount = GetPersonCount();
            
            this.curIndex = 0;
            CtrlPreNextBtnStatus();
            
            if (this.personCount > 0)
            {
                DisplayInfo(this.curIndex);
            }
            else
                ResetContrlsBesidesTab();

        }

        #region 人员界面控件操作响应处理
        //上一个按钮。
        private void buttonPrevious_Click(object sender, EventArgs e)
        {
            if (this.curIndex > 0)
                this.curIndex--;

            CtrlPreNextBtnStatus();

            ResetArmmanInfoTab();
            ResetStaffInfoTab();
            ResetWorkerInfoTab();
            ResetNCOInfoTab();
            ResetContrlsBesidesTab();

            DisplayInfo(this.curIndex);
        }

        //下一个按钮。
        private void buttonNext_Click(object sender, EventArgs e)
        {
            if (this.curIndex < this.personCount - 1)
                this.curIndex++;

            CtrlPreNextBtnStatus();

            ResetArmmanInfoTab();
            ResetStaffInfoTab();
            ResetWorkerInfoTab();
            ResetNCOInfoTab();
            ResetContrlsBesidesTab();

            DisplayInfo(this.curIndex);
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("删除当前人员?", "删除确认", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                //delete
                StringBuilder sql = new StringBuilder("delete person, personsortinfo from person left join personsortinfo on person.idperson = personsortinfo.idperson where person.idperson = '");
                sql.Append(this.curPerInfo.idperson.ToString());
                sql.Append("'");

                try
                {
                    DBProc.Instance().Excute(sql.ToString());

                    //数据库中总人数
                    personCount = GetPersonCount();

                    if (personCount > 0)
                    {
                        if (this.curIndex == personCount)
                            this.curIndex--;

                        //删除数据造成视图与personTable不一致，重新读取
                        this.personTable = null;
                        //MessageBox.Show("删除成功！", "删除");
                        DisplayInfo(this.curIndex);
                    }
                    else
                    {
                        //将当前信息清空
                        this.curPerInfo.idperson = 0;

                        //清空界面
                        ResetContrlsBesidesTab();

                        string type = tabControl.SelectedTab.Text;

                        if (type == "军人干部")
                            ResetArmmanInfoTab();
                        else if (type == "职员干部")
                            ResetStaffInfoTab();
                        else if (type == "工人")
                            ResetWorkerInfoTab();
                        else if (type == "高级士官")
                            ResetNCOInfoTab();
                        else
                        {
                        }

                        this.buttonPrevious.Enabled = false;
                        this.buttonNext.Enabled = false;
                        this.buttonDelete.Enabled = false;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        //清空当前人员信息
        private void ClearPersonInfo()
        {
            this.curPerInfo.idperson = 0;    
            this.curPerInfo.name = null;
            this.curPerInfo.type = PersonTypeEnum.Unknown;
            this.curPerInfo.sex = null;
            this.curPerInfo.unit = null;
            this.curPerInfo.adminDuty = null;
            this.curPerInfo.adminDutyTime = DateProc.InvalidDate();
            this.curPerInfo.techRank = null;
            this.curPerInfo.techRankTime = DateProc.InvalidDate();
            this.curPerInfo.techTitle = null;
            this.curPerInfo.techTitleTime = DateProc.InvalidDate();
            this.curPerInfo.curRankBeforeTime = DateProc.InvalidDate();
            this.curPerInfo.workTime = DateProc.InvalidDate();
            this.curPerInfo.schoolTime = DateProc.InvalidDate();
            this.curPerInfo.signupTime = DateProc.InvalidDate();
            this.curPerInfo.retirementTime = DateProc.InvalidDate();
            
            this.curPerInfo.marital = PersonMaritalEnum.Unknown;
            this.curPerInfo.workStatus = WorkStatusEnum.Unknown;
            this.curPerInfo.withArmy = WithArmyStatusEnum.Unkown;

            this.curPerInfo.curHousingAddr.addr = null;
            this.curPerInfo.curHousingAddr.area = null;
            this.curPerInfo.curHousingAddr.roomNum = null;
                
            this.curPerInfo.mateInfo.name = null;
            this.curPerInfo.mateInfo.rank = null;
            this.curPerInfo.mateInfo.unit = null;

            this.curPerInfo.remarks = null;

            this.curPerInfo.housingEligible = 0;                      
            this.curPerInfo.bothEmployee = 0;                         
            this.curPerInfo.evaluation = null;
        }

        bool addFlag = false;
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            addFlag = true;
            ResetArmmanInfoTab();
            ResetContrlsBesidesTab();
            ResetNCOInfoTab();
            ResetStaffInfoTab();
            ResetWorkerInfoTab();
            ClearPersonInfo();
            this.curPerInfo.housingInfo.Clear();
            this.curPerInfo.formerHousingId.Clear();
        }

        private void Add()
        {
            PersonTypeEnum type = DataDictionary.Instance().GetPersonType(tabControl.SelectedTab.Text);

            try
            {
                if (type == PersonTypeEnum.ArmMan)
                {
                    GetValueFromArmman(ref this.curPerInfo);
                }
                else if (type == PersonTypeEnum.Staff)
                {
                    GetValueFromStaff(ref this.curPerInfo);
                }
                else if (type == PersonTypeEnum.Worker)
                {
                    GetValueFromWorker(ref this.curPerInfo);
                }
                else if (type == PersonTypeEnum.NCO)
                {
                    GetValueFromNCO(ref this.curPerInfo);
                }
                else
                {
                    return;
                }

                this.curPerInfo.type = type;

                //name == null 表明数据转换时有问题，则不处理
                if (this.curPerInfo.name == null || this.curPerInfo.name == "")
                {
                    MessageBox.Show("创建人员必需要输入姓名");
                    return;
                }

                InfoSearcher infoSearcher = new InfoSearcher();
                //首先检查数据库中是否存在对应的记录，姓名单位性别，配偶姓名都相同
                if (infoSearcher.PersonExisted(this.curPerInfo))
                {
                    MessageBox.Show("数据库中已存在高度匹配的人员，请确认信息！");
                    return;
                }

                //清空房屋界面
                this.curPerInfo.housingInfo.Clear();
                this.curPerInfo.formerHousingId.Clear();

                string insertPersonInfoSql = this.sqlCreator.InsertSql(this.curPerInfo);

                this.curPerInfo.idperson = DBProc.Instance().ExcuteInsertSql(insertPersonInfoSql);

                if (this.curPerInfo.idperson > 0)
                {
                    //最后，生成该人员的排序信息并存入数据库
                    PersonSortInfoProc sortInfoProc = new PersonSortInfoProc();
                    sortInfoProc.Proc(this.curPerInfo);

                    //人员总数增加1
                    personCount++;
                }
                else
                {
                    MessageBox.Show("数据入库出现错误：无法获取人员id");
                }
                MessageBox.Show("增加成功！", "增加");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            this.personTable = null;
            this.curIndex = 0;
            DisplayInfo(this.curIndex);
            addFlag = false;
        }

        private void UpdatePerson()
        {
            PersonTypeEnum type = DataDictionary.Instance().GetPersonType(tabControl.SelectedTab.Text);
            this.curPerInfo.type = type;

            string sql = null;

            try
            {
                PersonSortInfoProc sortInfoProc = new PersonSortInfoProc();

                if (type == PersonTypeEnum.ArmMan)
                {
                    GetValueFromArmman(ref this.curPerInfo);
                    sql = this.sqlCreator.UpdateExceptHousing(this.curPerInfo);
                    //生成该人员的排序信息并存入数据库
                    sortInfoProc.Proc(this.curPerInfo);
                }
                else if (type == PersonTypeEnum.Staff)
                {
                    GetValueFromStaff(ref this.curPerInfo);
                    sql = this.sqlCreator.UpdateExceptHousing(this.curPerInfo);

                    sortInfoProc.Proc(this.curPerInfo);
                }
                else if (type == PersonTypeEnum.Worker)
                {
                    GetValueFromWorker(ref this.curPerInfo);
                    sql = this.sqlCreator.UpdateExceptHousing(this.curPerInfo);

                    sortInfoProc.Proc(this.curPerInfo);
                }
                else if (type == PersonTypeEnum.NCO)
                {
                    GetValueFromNCO(ref this.curPerInfo);
                    sql = this.sqlCreator.UpdateExceptHousing(this.curPerInfo);

                    sortInfoProc.Proc(this.curPerInfo);
                }
                else
                {
                }

                if (this.curPerInfo.name == null || this.curPerInfo.name == "")
                {
                    MessageBox.Show("修改人员必需要输入姓名");
                    return;
                }

                DBProc.Instance().Excute(sql);

                //每次修改数据并不是重新读取数据库，因此需要更新内存中的DataTable保持一致
                int index = this.curIndex % MAX_COUNT;
                UpdateDataTable(ref this.personTable, index, this.curPerInfo);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void buttonModify_Click(object sender, EventArgs e)
        {
            if (addFlag)
            {
                Add();
                return;
            }

            UpdatePerson();
            
            MessageBox.Show("修改成功！","修改");
        }

        //可分房
        private void checkBoxHousingEligible_Click(object sender, EventArgs e)
        {
            if (this.checkBoxHousingEligible.Checked)
            {
                this.curPerInfo.housingEligible = 1;
            }
            else
            {
                this.curPerInfo.housingEligible = 0;
            }
        }

        private void comboBoxMarital_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.comboBoxMarital.SelectedItem != null)
            {
                PersonMaritalEnum marital = DataDictionary.Instance().GetMorital(this.comboBoxMarital.Text);

                CtrlControlsStatusByMarital(marital);
            }
        }

        void CtrlControlsStatusByMarital(PersonMaritalEnum marital)
        {
            if (marital == PersonMaritalEnum.Unmarried
                    || marital == PersonMaritalEnum.DivorcedWithChild || marital == PersonMaritalEnum.DivorcedWithoutChild)
            {
                this.labelMateName.Enabled = false;
                this.labelMateRank.Enabled = false;
                this.labelMateUnit.Enabled = false;
                this.textBoxMateName.Enabled = false;
                this.textBoxMateRank.Enabled = false;
                this.textBoxMateUnit.Enabled = false;
            }
            else
            {
                this.labelMateName.Enabled = true;
                this.labelMateRank.Enabled = true;
                this.labelMateUnit.Enabled = true;
                this.textBoxMateName.Enabled = true;
                this.textBoxMateRank.Enabled = true;
                this.textBoxMateUnit.Enabled = true;
            }
        }

        private void CtrlPreNextBtnStatus()
        {

            if (this.curIndex > 0 && this.personCount > 0)
            {
                this.buttonPrevious.Enabled = true;
            }
            else
            {
                this.buttonPrevious.Enabled = false;
            }
            
            if (this.personCount > 0 && this.curIndex < this.personCount - 1)
            {
                buttonNext.Enabled = true;
            }
            else
            {
                buttonNext.Enabled = false;
            }
        }

        #endregion

        private void dataGridViewCurHousing_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int rowIndex = e.RowIndex;
            int colIndex = e.ColumnIndex;

            if (rowIndex < 0 || colIndex < 0)
                return;

            DataGridViewRow dr = this.dataGridViewCurHousing.Rows[rowIndex];
            string colName = this.dataGridViewCurHousing.Columns[colIndex].Name;

            //不是“checkintime”的item则忽略
            if (colName.Equals(DataDictionary.Instance().DGVNewColName(DGVNewColConsts.CHECKINTIME)))
            {
                int housingID = Convert.ToInt16(dr.Cells[DataDictionary.Instance().HousingTableFieldName(HousingColConsts.ID)].FormattedValue);

                FormSetCheckinTime form = new FormSetCheckinTime(housingID, this.UpdateCheckintime);
                form.ShowDialog();
            }
        }

        private void UpdateCheckintime(int idhousing, DateTime checkinTime)
        {
            List<HousingOccupancyInfo> housingInfo = this.curPerInfo.housingInfo;

            for (int i = 0; i < housingInfo.Count; i++)
            {
                if (housingInfo[i].id == idhousing)
                {
                    HousingOccupancyInfo info;
                    info.id = housingInfo[i].id;
                    info.checkinTime = checkinTime;

                    housingInfo[i] = info;

                    //更新数据库
                    string sql = this.sqlCreator.UpdateOnlyForHousingInfo(this.curPerInfo);
                    DBProc.Instance().Excute(sql);

                    //更新当前的内存中的DataTable， 以维护数据的一致性
                    //刷新界面
                    UpdatePersonHousingInfo();

                    break;
                }
            }
        }

        //显示上一套住房
        private void buttonHistory_Click(object sender, EventArgs e)
        {
            if (this.curPerInfo.formerHousingId != null)
            {
                FormFormerHouse historyHouse = new FormFormerHouse();
                historyHouse.HisrotyHouse(this.curPerInfo.formerHousingId);
                historyHouse.ShowDialog();
            }
        }

        //选房
        private void buttonHouse_Click(object sender, EventArgs e)
        {
            FormHousingSelect housingSelect = new FormHousingSelect(this.curPerInfo, this.UpdatePersonHousingInfo);
            housingSelect.ShowDialog();
        }

        public delegate void UpdateCheckintimeDelegete(int idhousing, DateTime checkinTime);

        //临时按钮，只更新配偶姓名首字母。
        private void buttonUpdateMatenameInitial_Click(object sender, EventArgs e)
        {
            string s = "select mateName from person";
            string s2 = null;
            DataTable d = DBProc.Instance().ReadData(s).Tables[0];
            for (int i = 0; i < d.Rows.Count; i++)
            {
                s2 = d.Rows[i][0].ToString();
                string s4 = Spell.MakeSpellCode(s2, SpellOptions.FirstLetterOnly);
                string s3 = "update person set mateNameInitial='" + s4 + "' where mateName='" + s2 + "'";
                DBProc.Instance().Excute(s3);
            }
            MessageBox.Show("配偶姓名首字母更新完毕！");
        }

        #region 自动保存
        private void ControlsLeave(object sender, EventArgs e)
        {
            if (valueChanged)
            {
                UpdatePerson();
                Console.WriteLine("Update person");
                valueChanged = false;
            }
            else
            {
                Console.WriteLine("No changes");
            }
        }

        private void ControlsValueChanged(object sender, EventArgs e)
        {
            valueChanged = true;
        }

        bool valueChanged = false;
        #endregion
    }
}
